package com.shiwaixiangcun.customer.ui.activity


import android.Manifest
import android.annotation.SuppressLint
import android.content.Intent
import android.content.pm.PackageManager
import android.content.res.Configuration
import android.content.res.Resources
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.support.v4.app.ActivityCompat
import android.support.v4.content.ContextCompat
import android.text.TextUtils
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import com.shiwaixiangcun.customer.ConfigSps
import com.shiwaixiangcun.customer.R
import com.shiwaixiangcun.customer.app.App
import com.shiwaixiangcun.customer.base.BaseActivity
import com.shiwaixiangcun.customer.entity.AlertJumpServiceDetail
import com.shiwaixiangcun.customer.entity.AlertJunptoBean
import com.shiwaixiangcun.customer.entity.AlertPhoneBean
import com.shiwaixiangcun.customer.interfaces.RequestPermissionType
import com.shiwaixiangcun.customer.module.homeservice.CategoryListActivity
import com.shiwaixiangcun.customer.module.homeservice.ServiceDetailActivity
import com.shiwaixiangcun.customer.ui.dialog.DialogLoginOut
import com.shiwaixiangcun.customer.utils.AppSharePreferenceMgr
import com.shiwaixiangcun.customer.utils.JsonUtil
import com.shiwaixiangcun.customer.widget.X5WebView
import com.tencent.smtt.export.external.interfaces.JsResult
import com.tencent.smtt.sdk.WebChromeClient
import com.tencent.smtt.sdk.WebView
import com.tencent.smtt.sdk.WebViewClient
import kotlinx.android.synthetic.main.activity_common_web.*
import kotlinx.android.synthetic.main.top_bar_white.*
import java.util.*


/**
 * 通用的网页请求页面
 */
class CommonWebActivity : BaseActivity(), View.OnClickListener {


    private var pageName: String? = null

    private var phoneNumber: String? = null
    private var requestUrl: String? = null
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_common_web)
        initBundleData()
        initWebView()
        initViewAndEvent()
    }


    /**
     * 初始化传递过来的数据
     */
    private fun initBundleData() {

        requestUrl = intent.extras.getString("h5_url")
        pageName = intent.extras.getString("h5_name")
    }



    @SuppressLint("SetJavaScriptEnabled")
    private fun initWebView() {
        x5WebView.webChromeClient = MyWebChromeViewClient()
        x5WebView.webViewClient = MyWebViewClient()
        val siteId = AppSharePreferenceMgr.get(App.getContext(), ConfigSps.CURRENT_SITE_ID, 20) as Int
        val header = HashMap<String, String>()

        header["siteId"] = "" + siteId
        x5WebView.loadUrl(requestUrl, header)
        x5WebView.setOnScrollChangeListener(object : X5WebView.OnScrollChangeListener {
            override fun onPageEnd(l: Int, t: Int, oldl: Int, oldt: Int) {
            }

            override fun onPageTop(l: Int, t: Int, oldl: Int, oldt: Int) {
            }

            override fun onScrollChanged(l: Int, t: Int, oldl: Int, oldt: Int) {
            }

            override fun scrollDistance(distant: Float) {
            }
        })

    }



    private fun initViewAndEvent() {
        tv_page_name.text = pageName
        back_left.setOnClickListener(this)


    }

    private inner class MyWebChromeViewClient : WebChromeClient() {

        override fun onJsAlert(view: WebView?, url: String?, message: String?, result: JsResult?): Boolean {
            val bundle = Bundle()
            when {

            //拨打电话
                message?.contains("phone", true)!! -> {
                    val phoneBean = JsonUtil.fromJson<AlertPhoneBean>(message, AlertPhoneBean::class.java)
                    phoneNumber = phoneBean.data.phone
                    showDialog(phoneBean.data.phone)
                    result?.confirm()
                    return true
                }

                message.contains("TO_HOME_SERVICE_DETAIL", true) -> {
                    val fromJson = JsonUtil.fromJson<AlertJumpServiceDetail>(message, AlertJumpServiceDetail::class.java)
                    if (fromJson.data.detailId != null) {
                        bundle.putLong("serviceId", fromJson.data.detailId)
                        readyGo(ServiceDetailActivity::class.java, bundle)
                    } else {
                        bundle.putLong("type", fromJson.data.typeId)
                        bundle.putString("name", fromJson.data.name)
                        readyGo(CategoryListActivity::class.java, bundle)

                    }
                    result?.confirm()
                    return true
                }
                else -> {
                    val jumpBean = JsonUtil.fromJson<AlertJunptoBean>(message, AlertJunptoBean::class.java)

                    bundle.putString("h5_url", jumpBean.data.url)
                    bundle.putString("h5_name", jumpBean.data.title)
                    if (!TextUtils.isEmpty(jumpBean.data.url)) {
                        readyGo(CommonWebActivity::class.java, bundle)
                    }
                    result?.confirm()
                    return true
                }

            }
        }

        override fun onProgressChanged(view: WebView, newProgress: Int) {
            if (newProgress == 100) {
                myProgressBar.visibility = View.GONE
            } else {
                if (View.INVISIBLE == myProgressBar.visibility) {
                    myProgressBar.visibility = View.VISIBLE
                }
                myProgressBar.progress = newProgress
            }
            super.onProgressChanged(view, newProgress)
        }


    }

    /**
     * 处理通知 ，请求事件
     */
    private inner class MyWebViewClient : WebViewClient() {
        override fun shouldOverrideUrlLoading(view: WebView, url: String): Boolean {
            view.loadUrl(url)
            return true
        }

    }

    override fun onClick(v: View) {
        when (v.id) {
            R.id.back_left -> finish()
            else -> {
            }
        }


    }


    override fun onDestroy() {
        if (x5WebView != null) {
            x5WebView.loadDataWithBaseURL(null, "", "text/html", "utf-8", null)
            x5WebView.clearHistory()

            (x5WebView.parent as ViewGroup).removeView(x5WebView)
            x5WebView.destroy()

        }
        super.onDestroy()
    }


    override fun getResources(): Resources {
        val res = super.getResources()
        val config = Configuration()
        config.setToDefaults()
        res.updateConfiguration(config, res.displayMetrics)
        return res
    }



    private fun showDialog(phoneNumber: String) {
        val dialogLoginOut = DialogLoginOut(mContext, R.layout.item_dialog_call_phone)
        dialogLoginOut.setTitle("是否要拨打此电话？")
        dialogLoginOut.setMessage(phoneNumber)

        dialogLoginOut.setYesOnclickListener("是", DialogLoginOut.OnPositiveOnclickListener {
            dialogLoginOut.dismiss()
            requestPermission(phoneNumber)
        })

        dialogLoginOut.setNoOnclickListener("否") { dialogLoginOut.dismiss() }
        dialogLoginOut.show()
    }

    private fun requestPermission(number: String?) {
        //判断Android版本是否大于23
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            val checkCallPhonePermission = ContextCompat.checkSelfPermission(this, Manifest.permission.CALL_PHONE)

            if (checkCallPhonePermission != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.CALL_PHONE),
                        RequestPermissionType.REQUEST_CODE_ASK_CALL_PHONE)
                return
            } else {
                callPhone(number)
            }
        } else {
            callPhone(number)
        }
    }


    /**
     * 注册权限申请回调
     * @param requestCode 申请码
     * @param permissions 申请的权限
     * @param grantResults 结果
     */
    @Override
    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<String>, grantResults: IntArray) {
        when (requestCode) {
            RequestPermissionType.REQUEST_CODE_ASK_CALL_PHONE -> if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                callPhone(phoneNumber)
            } else {
                // Permission Denied
                Toast.makeText(this, "CALL_PHONE Denied", Toast.LENGTH_SHORT).show()
            }
            else -> super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        }
    }

    /**
     * 拨号方法
     */
    @SuppressLint("MissingPermission")
    private fun callPhone(number: String?) {
        val intent = Intent(Intent.ACTION_CALL, Uri.parse("tel:" + number))
        intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
        startActivity(intent)
    }

}
